import cv2
import numpy as np
import os


import cv2

def compare_images_sift(img1_path, img2_path):
    img1 = cv2.imread(img1_path, cv2.IMREAD_GRAYSCALE)
    img2 = cv2.imread(img2_path, cv2.IMREAD_GRAYSCALE)

    sift = cv2.SIFT_create()

    # 计算关键点和特征描述符
    kp1, des1 = sift.detectAndCompute(img1, None)
    kp2, des2 = sift.detectAndCompute(img2, None)

    # FLANN 匹配器
    index_params = dict(algorithm=1, trees=5)
    search_params = dict(checks=50)
    flann = cv2.FlannBasedMatcher(index_params, search_params)

    matches = flann.knnMatch(des1, des2, k=2)

    # 过滤良好匹配项
    good_matches = []
    for m, n in matches:
        if m.distance < 0.75 * n.distance:
            good_matches.append(m)

    similarity = len(good_matches) / max(len(kp1), len(kp2))
    return similarity


def get_jpg_images(folder_path):
    images = [f for f in os.listdir(folder_path) if f.lower().endswith('.jpg')]
    return images



source_image_dir = "/Users/daxiang/Downloads/qiqi_mini"
target_image_dir = "/Users/daxiang/Downloads/qiqi_mini/初修"

source_images = get_jpg_images(source_image_dir)
target_images = get_jpg_images(target_image_dir)


result = list()
for source_image in source_images :
    sub = list()
    for  target_image in target_images:
        source_path = f"{source_image_dir}/{source_image}"
        target_path = f"{target_image_dir}/{target_image}"
        similarity = compare_images_sift(target_path, source_path)
        sub.append(dict(s = source_image, t=target_image, similarity=similarity))
        print("---------相似度:", similarity)
    result.append(dict(s = source_image, data = sub))



final_res = list()
for item in result:
    data = item["data"]
    min_abs_value = max([num["similarity"] for num in data])
    data_item = [aa for aa in data if aa["similarity"] == min_abs_value]
    final_res.append(data_item)

print("---------final_res:", final_res)

